<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>rgb转16进制</title>
</head>
<style>
    div {
        color: rgb(255, 192, 204);
        color: #ffc2cc;
        color: rgba(255, 194, 204, .6);
        color: #ffc2cc99;
        color: #ffdae0;
    }
</style>

<body>

</body>
<script>
    // rgb转16进制
    const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    console.log(rgbToHex(0, 0, 0))
    console.log(rgbToHex(255, 194, 204))
    // or
    const rgbToHex2 = (str) => {
        let reg = /^(rgb|RGB)/;
        if (!reg.test(str)) { return; }
        var arr = str.slice(4, str.length - 1).split(",")
        let color = '#';
        for (var i = 0; i < arr.length; i++) {
            var t = Number(arr[i]).toString(16)
            if (t == "0") {   //如果为“0”的话，需要补0操作,否则只有5位数
                t = t + "0"
            }
            color += t;
        }
        return color;
    }
    console.log(rgbToHex2('rgb(255, 194, 204)'))

    // 16-rgb
    const hexToRgb = (str) => {
        var reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
        if (!reg.test(str)) { return; }
        let newStr = (str.toLowerCase()).replace(/\#/g, '')
        let len = newStr.length;
        if (len == 3) {
            let t = ''
            for (var i = 0; i < len; i++) {
                t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
            }
            newStr = t
        }
        let arr = []; //将字符串分隔，两个两个的分隔
        for (var i = 0; i < 6; i = i + 2) {
            let s = newStr.slice(i, i + 2)
            arr.push(parseInt("0x" + s))
        }
        return 'rgb(' + arr.join(",") + ')';
    }
    console.log(hexToRgb('#ffc2cc'))

</script>

</html>